package com.neu.web.controller.common;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.PageInfo;
import com.neu.common.annotation.Anonymous;
import com.neu.common.constant.HttpStatus;
import com.neu.common.core.domain.AjaxResult;
import com.neu.common.core.page.TableDataInfo;
import com.neu.common.exception.UtilException;
import com.neu.system.domain.NeuAir;
import com.neu.system.domain.NeuCity;
import com.neu.system.domain.vo.NeuAirVO;
import com.neu.system.service.INeuAirService;
import com.neu.system.constant.RedisConstant;
import com.neu.system.service.INeuAirTypeService;
import com.neu.system.service.INeuCityService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static com.neu.common.utils.PageUtils.startPage;

@RestController
@RequestMapping("/show")
public class commonShowController {

    @Autowired
    private INeuAirService airService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private INeuCityService cityService;

    @Autowired
    private INeuAirTypeService airTypeService;

    @Anonymous
    @GetMapping("/color")
    public AjaxResult GetAllColor() {
        List<String> color = airTypeService.getAllColor();
        return AjaxResult.success(color);
    }


    /**
     * 分页获取当天各个城市的空气质量信息，默认第一页（pageNum），每页10条数据（pageSize）
     * @return
     */
    @Anonymous
    @GetMapping("/max/page")
    public TableDataInfo showPageMaxAir() {

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化日期为字符串
        String formattedDate = currentDate.format(formatter);

        NeuAir neuAir = new NeuAir();
        neuAir.setQueryCreateTime(formattedDate);

        startPage();
        List<NeuAirVO> list = airService.selectNeuAirList(neuAir);

        TableDataInfo dataTable = getDataTable(list);
        Long total = airService.selectCount(neuAir);
        dataTable.setTotal(total);

        return dataTable;
    }

    /**
     * 获取当天各个城市的空气质量信息
     * @return
     */
    @Anonymous
    @GetMapping("/max")
    public AjaxResult showMaxAir() {

        String key = RedisConstant.TODAY_AIR_DATA;
        // 从redis中获取数据
        String json = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(json)) {
            List<NeuAirVO> neuAirVOS = JSONUtil.parseArray(json).toList(NeuAirVO.class);
            return AjaxResult.success(neuAirVOS);
        }

        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 定义日期格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        // 格式化日期为字符串
        String formattedDate = currentDate.format(formatter);

        NeuAir neuAir = new NeuAir();
        neuAir.setQueryCreateTime(formattedDate);

        List<NeuAirVO> list = airService.selectNeuAirList(neuAir);
        // 存进redis
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(list));
        redisTemplate.expire(key, 15, TimeUnit.HOURS);

        return AjaxResult.success(list);
    }

    /**
     * 根据id查询城市空气信息
     * @param id 要查询的id
     * @return
     */
    @Anonymous
    @GetMapping("/{id}")
    public AjaxResult getAirDataById(@PathVariable("id") Long id) {

        String key = RedisConstant.TODAY_AIR_DATA + ":" + id;

        String json = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(json)) {
            NeuAirVO neuAirVO = JSONUtil.toBean(json, NeuAirVO.class);
            return AjaxResult.success(neuAirVO);
        }

        NeuAirVO neuAirVO = airService.selectNeuAirVoById(id);

        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(neuAirVO));
        redisTemplate.expire(key, 30, TimeUnit.MINUTES);

        return AjaxResult.success(neuAirVO);
    }

    /**
     * 获取当天某个城市的空气质量信息
     * @return
     */
    @Anonymous
    @GetMapping("/city/{id}")
    public AjaxResult showMaxAirByCity(@PathVariable("id") Long id) {

        NeuAir neuAir = new NeuAir();
        neuAir.setCityId(id);

        // 查询某个城市的历史十五天数据
        List<NeuAirVO> list = airService.selectNeuAirListByCity(neuAir);

        return AjaxResult.success(list);
    }

    @Anonymous
    @GetMapping("/city/name/{name}")
    public AjaxResult getCityByName(@PathVariable("name") String name) {

        Long cityId = cityService.selectCityByCityName(name);

        if (cityId == null) {
            throw new UtilException("暂无该城市");
        }
        return AjaxResult.success(cityId);
    }

    @Anonymous
    @ApiOperation("获取城市列表")
    @GetMapping("/list")
    public AjaxResult list(NeuCity neuCity)
    {
        String key = RedisConstant.TODAY_AIR_CITY;

        String json = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotEmpty(json)) {
            List<NeuCity> cityList = JSONUtil.parseArray(json).toList(NeuCity.class);
            return AjaxResult.success(cityList);
        }

        List<NeuCity> list = cityService.selectNeuCityList(neuCity);

        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(list));
        redisTemplate.expire(key, 15, TimeUnit.HOURS);

        return AjaxResult.success(list);
    }

    /**
     * 响应请求分页数据
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
    protected TableDataInfo getDataTable(List<?> list)
    {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(list);
        rspData.setTotal(new PageInfo(list).getTotal());
        return rspData;
    }

    @Anonymous
    @GetMapping("/yes")
    public void test1() {
        airService.test();
    }
}
